package org.smart4j.framework.helper;

/**
 * Created by liangyue on 2018/1/8.
 */

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smart4j.framework.util.CollectionUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 数据库操作助手类
 */
public final class DatabaseHelper {
	private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);
	private static final QueryRunner QUERY_RUNNER;
	private static final ThreadLocal<Connection> CONNECTION_HOLDER;
	private static final BasicDataSource DATA_SOURCE;

	static {
		CONNECTION_HOLDER = new ThreadLocal<>();
		QUERY_RUNNER = new QueryRunner();
		String driver = ConfigHelper.getJdbcDriver();
		String url = ConfigHelper.getJdbcUrl();
		String username = ConfigHelper.getJdbcUsername();
		String password = ConfigHelper.getJdbcPassword();

		DATA_SOURCE = new BasicDataSource();
		DATA_SOURCE.setDriverClassName(driver);
		DATA_SOURCE.setUrl(url);
		DATA_SOURCE.setUsername(username);
		DATA_SOURCE.setPassword(password);
	}


	/**
	 * 获取数据库连接
	 * @return
	 */
	public static Connection getConnection(){
		Connection conn = CONNECTION_HOLDER.get();
		if (conn == null){
			try {
				conn = DATA_SOURCE.getConnection();
			} catch (SQLException e) {
				LOGGER.error("get connection failure", e);
				throw new RuntimeException();
			}finally {
				CONNECTION_HOLDER.set(conn);
			}
		}

		return conn;
	}
	/**
	 * 查询实体列表
	 * @param entityClass
	 * @param sql
	 * @param params
	 * @param <T>
	 * @return
	 */
	public static <T>List<T> queryEntityList(Class<T> entityClass, String sql, Object... params){
		List<T> entityList;
		try {
			Connection connection = getConnection();
			entityList = QUERY_RUNNER.query(connection, sql, new BeanListHandler<T>(entityClass), params);
		} catch (SQLException e) {
			LOGGER.error("query entity list failure", e);
			throw new RuntimeException();
		}
		return entityList;
	}

	/**
	 * 查询实体
	 * @param entityClass
	 * @param sql
	 * @param params
	 * @param <T>
	 * @return
	 */
	public static <T> T queryEntity(Class<T> entityClass, String sql, Object... params){
		T entity;
		try {
			Connection connection = getConnection();
			entity = QUERY_RUNNER.query(connection, sql, new BeanHandler<T>(entityClass), params);
		} catch (SQLException e) {
			LOGGER.error("query entity failure", e);
			throw new RuntimeException();
		}
		return entity;
	}

	/**
	 * 执行查询语句
	 * @param sql
	 * @param params
	 * @return
	 */
	public static List<Map<String, Object>> excuteQuery(String sql, Object... params){
		List<Map<String, Object>> result;
		try {
			Connection connection = getConnection();
			result = QUERY_RUNNER.query(connection, sql, new MapListHandler(), params);
		} catch (SQLException e) {
			LOGGER.error("excute query failure", e);
			throw new RuntimeException();
		}
		return result;
	}

	/**
	 * 执行更新语句，包括（update、insert、delete）
	 * @param sql
	 * @param params
	 * @return
	 */
	public static int excuteUpdate(String sql, Object... params){
		int rows = 0;
		try {
			Connection connection = getConnection();
			rows = QUERY_RUNNER.update(connection, sql, params);
		} catch (SQLException e) {
			LOGGER.error("excute update failure", e);
			throw new RuntimeException();
		}
		return rows;
	}


	/**
	 * 插入实体
	 * @param entityClass
	 * @param fieldMap
	 * @param <T>
	 * @return
	 */
	public static <T> boolean insertEntity(Class<T> entityClass, Map<String, Object> fieldMap){
		if (CollectionUtil.isEmpty(fieldMap)){
			LOGGER.error("can not insert entity : fieldmap is empty");
			return false;
		}

		String sql = "insert into " + getTableName(entityClass);
		StringBuilder columns = new StringBuilder("(");
		StringBuilder values = new StringBuilder("(");
		for (String fieldName : fieldMap.keySet()){
			columns.append(fieldName).append(", ");
			values.append("?, ");
		}
		columns.replace(columns.lastIndexOf(","), columns.length(), ")");
		values.replace(values.lastIndexOf(","), values.length(), ")");
		sql = columns + "values" + values;

		Object[] params = fieldMap.values().toArray();
		return excuteUpdate(sql, params) == 1;

	}

	/**
	 * 更新实体
	 * @param entityClass
	 * @param fieldMap
	 * @param <T>
	 * @return
	 */
	public static <T> boolean updateEntity(Class<T> entityClass, long id, Map<String, Object> fieldMap){
		if (CollectionUtil.isEmpty(fieldMap)){
			LOGGER.error("can not update entity : fieldmap is empty");
			return false;
		}
		String sql = "update " + getTableName(entityClass) + "set";
		StringBuilder columns = new StringBuilder();
		for (String fieldName : fieldMap.keySet()){
			columns.append(fieldName).append("=? ");
		}
		sql += columns.substring(0, columns.lastIndexOf(", ")) + "where id = ?";

		List<Object> paramList = new ArrayList<>();
		paramList.addAll(fieldMap.values());
		paramList.add(id);
		Object[] params = fieldMap.values().toArray();
		return excuteUpdate(sql, params) == 1;

	}



	/**
	 * 更新实体
	 * @param entityClass
	 * @param <T>
	 * @return
	 */
	public static <T> boolean deleteEntity(Class<T> entityClass, long id){
		String sql = "delete from " + getTableName(entityClass) + "where id = ?";
		return excuteUpdate(sql, id) == 1;

	}

	private static String getTableName(Class<?> entityClass){
		return entityClass.getSimpleName();
	}


	/**
	 * 开启事务
	 * 默认是自动提交事务的，所以需要将自动提交设置为false
	 * 在开启事务完毕后，需要将Connection对象放入本地线程变量中，
	 * 事务提交或回滚后，需要移除本地线程变量中的Connection对象
	 */
	public static void beginTransaction(){
		Connection conn = getConnection();
		if (conn != null){
			try {
				conn.setAutoCommit(false);
			} catch (SQLException e) {
				LOGGER.error("begin transaction failure", e);
				throw new RuntimeException(e);
			}finally {
				CONNECTION_HOLDER.set(conn);
			}
		}
	}

	/**
	 * 提交事务
	 */
	public static void commitTransaction(){
		Connection conn = getConnection();
		if (conn != null){
			try {
				conn.commit();
				conn.close();
			} catch (SQLException e) {
				LOGGER.error("commit transaction failure", e);
				throw new RuntimeException(e);
			}finally {
				CONNECTION_HOLDER.remove();
			}
		}
	}

	/**
	 * 回滚事务
	 */
	public static void rollbackTransaction(){
		Connection conn = getConnection();
		if (conn != null){
			try {
				conn.rollback();
				conn.close();
			} catch (SQLException e) {
				LOGGER.error("rollback transaction failure", e);
				throw new RuntimeException(e);
			}finally {
				CONNECTION_HOLDER.remove();
			}
		}
	}
}
